class happyLocalStorage {
  constructor() {}

  introduce(){
    console.log(`
      1.本库提供设置、获取、删除、删除全部四个方法
        1.1-hl.setLocalStorage-使用详情请看hl.setLocalStorageIntroduce()
        1.2-hl.getLocalStorage('字符串类型')
        1.3-hl.delLocalStorage('字符串类型')
        1.4-hl.delAllLocalStorage()
    `);
  }

  judgeDataType(val) {//判断数据类型
    return Object.prototype.toString.call(val).slice(8, -1);
  }

  _delLocalStorage(getName) {//删除已经过期的LocalStorage
    let getLocalStorageValue = localStorage.getItem(getName);

    try {
      getLocalStorageValue = JSON.parse(getLocalStorageValue);
    } catch (error) {
      getLocalStorageValue = getLocalStorageValue;
    };
    
    if (this.judgeDataType(getLocalStorageValue) == "Object" && !!getLocalStorageValue._effectiveTime) {
      let effectiveTime = new Date(getLocalStorageValue._effectiveTime).getTime();
      if (new Date().getTime() - effectiveTime > 0) {//当前时间戳超过了有效时间戳-过期
        localStorage.removeItem(getName);
      }else{
        this[getName]=setTimeout(()=>{//开启定时器
          localStorage.removeItem(getName);
        },effectiveTime-new Date().getTime())
      }
    }
  }

  _initLocalStorage() {//初始化
    let len = localStorage.length;  // 获取长度
    let arr = [];
    if (len > 0) {
      for (let i = 0; i < len; i++) {
        let getKey = localStorage.key(i);
        arr.push(getKey);
      };
      arr.forEach(item => {//这里面存储的一定是有值的LocalStorage
        this._delLocalStorage(item)
      })
    };
  }

  /**
   * setLocalStorage使用说明
   */
  setLocalStorageIntroduce(){
    console.log(
      `
        1.不输入第三个参数或者输入null,就是一个正常的localStorage,支持设置复杂数据类型
        2.第三个参数为{},默认的过期时间就是15分钟
        3.第三个参数为{timeSize:"'年'/'月'/'日'/'时'/'分'/'秒'",timeSize:数字类型}
        4.例子-hl.setLocalStorage(name,{name:'张三},{timeSize:'分',timeSize:20})
      `
    )
  }
  /**
   * 功能:设置LocalStorage的值和过期时间
   * @param {*} setName:设置的名称 string
   * @param {*} setValue:设置的值 any
   * @param {*} expiresObj:过期时间 {}/{timeScale:'秒/分/时 日/月/年',timeSize:number} 
   */
  setLocalStorage(setName, setValue, expiresObj = null) {
    if (expiresObj == null) {//如果用户不输入第三个参数或者输入null，就是一个正常的localStorage
      let JSONStringify = JSON.stringify(setValue);
      localStorage.setItem(setName, JSONStringify);
    } else {//这里面输出的一定是一个已经JSON.stringify好的对象
      if (Object.keys(expiresObj).length == 0) {//输入的是一个空对象 设置默认过期时间:15分钟
        let newDate = new Date();//获取当前的时间对象
        let nowTimeStamp = newDate.getTime();//获取当前时间对象的时间戳
        nowTimeStamp += (1000 * 60 * 15);//将现在的时间戳和设置过期时间期间产生的时间戳 累加
        newDate.setTime(nowTimeStamp);//将累加的时间戳设置到过期时间上
        expiresObj[setName] = setValue;//将传入的名称和值以key/value的形式挂载到expiresObj上
        expiresObj._effectiveTime = newDate;//将累加好的时间挂载到expiresObj
        let stringifyExpiresObj = JSON.stringify(expiresObj);//将expiresObj转成字符串
        localStorage.setItem(setName, stringifyExpiresObj);//设置localStorage
        
        clearTimeout(this[setName])
        this[setName]=setTimeout(() => {//页面一直开着，到了过期时间就删掉
          this.delLocalStorage(setName);
        }, 1000 * 60 * 15);

      } else {//输入的不是空对象
        let newDate = new Date();
        let nowTimeStamp = newDate.getTime();
        let timeout = null;
        switch (expiresObj.timeScale) {//判断时间规格
          case '秒':
            nowTimeStamp += (1000 * parseFloat(expiresObj.timeSize));
            timeout = (1000 * parseFloat(expiresObj.timeSize));
            break;
          case '分':
            nowTimeStamp += (1000 * 60 * parseFloat(expiresObj.timeSize));
            timeout = (1000 * 60 * parseFloat(expiresObj.timeSize));
            break;
          case '时':
            nowTimeStamp += (1000 * 60 * 60 * parseFloat(expiresObj.timeSize));
            timeout = (1000 * 60 * 60 * parseFloat(expiresObj.timeSize));
            break;
          case '日':
            nowTimeStamp += (1000 * 60 * 60 * 24 * parseFloat(expiresObj.timeSize));
            timeout = (1000 * 60 * 60 * 24 * parseFloat(expiresObj.timeSize));
            break;
          case '月':
            nowTimeStamp += (1000 * 60 * 60 * 24 * 30 * parseFloat(expiresObj.timeSize));
            timeout = (1000 * 60 * 60 * 24 * 30 * parseFloat(expiresObj.timeSize));
            break;
          case '年':
            nowTimeStamp += (1000 * 60 * 60 * 24 * 30 * 12 * parseFloat(expiresObj.timeSize));
            timeout = (1000 * 60 * 60 * 24 * 30 * 12 * parseFloat(expiresObj.timeSize));
            break;

          default:
            break;
        }
        newDate.setTime(nowTimeStamp);//将累加的时间戳设置到过期时间上
        expiresObj[setName] = setValue;
        expiresObj._effectiveTime = newDate;
        let stringifyExpiresObj = JSON.stringify(expiresObj);
        localStorage.setItem(setName, stringifyExpiresObj);

        clearTimeout(this[setName])
        this[setName]=setTimeout(() => {
          this.delLocalStorage(setName);
        }, timeout);
      }
    }
  }

  /**
   * 功能:获取LocalStorage的值
   * @param {*} getName:获取的名称
   */
  getLocalStorage(getName) {
    let getLocalStorageValue = localStorage.getItem(getName);

    try {
      getLocalStorageValue = JSON.parse(getLocalStorageValue);
    } catch (error) {
      getLocalStorageValue = getLocalStorageValue;
    };

    if (this.judgeDataType(getLocalStorageValue) == "Object" && !!getLocalStorageValue._effectiveTime) {
      let effectiveTime = new Date(getLocalStorageValue._effectiveTime).getTime();//获取当初设置的时候的过期时间时间戳
      if (new Date().getTime() - effectiveTime < 0) {//如果当前的时间戳<当初设置的时候的过期时间时间戳 证明：没过期
        return getLocalStorageValue[getName];
      } else {//过期
        localStorage.removeItem(getName);
        return null;
      }
    } else {
      return getLocalStorageValue;
    }
  }

  delLocalStorage(name) {//删除指定的LocalStorage
    if(this.judgeDataType(name) === "String"){
      localStorage.removeItem(name);
    }else{
      console.error(`${name}的类型不是字符串,请输入字符串...`);
    }
  }

  delAllLocalStorage() {//删除全部的LocalStorage
    localStorage.clear();
  }
}

let hl = new happyLocalStorage();
hl._initLocalStorage();

export {
  hl
}